﻿using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Inovout.Serializer
{
    public class InterfaceContractResolver : CamelCasePropertyNamesContractResolver
    {
        private readonly Type interfaceType;
        public InterfaceContractResolver(Type type)
        {
            if (type.IsGenericType)
            {
                this.interfaceType = type.GetGenericArguments()[0];
            }
            else
            {
                this.interfaceType = type;
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {

            char[] chars = propertyName.ToCharArray();
            List<char> propertyNameChars = new List<char>();
            for (int i = 0; i < chars.Length; i++)
            {
                if (i == 0)
                {
                    propertyNameChars.Add(char.ToLower(chars[i], CultureInfo.InvariantCulture));
                }
                else if (char.IsUpper(chars[i]))
                {
                    propertyNameChars.Add('_');
                    propertyNameChars.Add(char.ToLower(chars[i], CultureInfo.InvariantCulture));
                }
                else
                {
                    propertyNameChars.Add(chars[i]);

                }
            }

            return new string(propertyNameChars.ToArray());
        }
        //protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        //{
        //    IList<JsonProperty> properties = base.CreateProperties(type.IsInterface ? type :
        //        interfaceType, memberSerialization);
        //    return properties;
        //}
    }

}
